package com.itboye.lottery.fragment;


import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.ObservableScrollView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.itboye.bylibrary.util.ScreenUtil;
import com.itboye.bylibrary.widget.glide.GlideUtil;
import com.itboye.lottery.base.BaseFragment;
import com.itboye.lottery.R;
import com.itboye.lottery.activity.BangDanActivity;
import com.itboye.lottery.activity.follow.HotPeopleInfoActivity;
import com.itboye.lottery.adapter.CommonPagerAdapter;
import com.itboye.lottery.alert.ByAlert;
import com.itboye.lottery.bean.PeopleBean;
import com.itboye.lottery.fragment.gendan.GendanCaseJine;
import com.itboye.lottery.presenter.UserPresenter;
import com.itboye.lottery.retrofit.ResponseCallback;
import com.itboye.lottery.view.frag_vp_frag.PersonalViewpager;

import org.jetbrains.annotations.NotNull;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/11/10.
 */

public class GenDanFragment extends BaseFragment implements ResponseCallback {

    private int position;
    RecyclerView rv_fragment_find;

    List<Fragment> orderFragments;
    PersonalViewpager vp_gendan;
    TabLayout tab_gendan;
    LinearLayout ll_hot_user;
    TextView tv_more_hot_people;
    ArrayList<PeopleBean> ar = new ArrayList<>();
    UserPresenter userPresenter = new UserPresenter(this);
    public PullToRefreshScrollView pull_to_refresh_scrollView;
    ObservableScrollView scrollView;
    TabLayout tab_gendan_2;
    private int maxDiff = 0;
    LinearLayout lay_transroot;
    private int topLayoutHeight = 0;
    private int statusBarHeight = 0;
    TextView iv_my_attention,tv_hot_gendan,tv_no_hot_people;
    private boolean isInit=false;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_gendan;
    }

    @Override
    protected void initData() {
//        showDialog();

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        System.out.println("用户可见？"+isVisibleToUser);
        if (isVisibleToUser&&!isInit) {
            isInit=true;
            topLayoutHeight = ScreenUtil.getMeasureHeight(lay_transroot);
            getFollowIndex();
            //init
            initRecyclerViewData();
            initHotPeopleData();
            vp_gendan.setAdapter(new CommonPagerAdapter(getActivity(), orderFragments, R.array.OrderTitles, getChildFragmentManager()));
            vp_gendan.setOffscreenPageLimit(5);
            tab_gendan.setupWithViewPager(vp_gendan);
            tab_gendan_2.setupWithViewPager(vp_gendan);
            vp_gendan.setCurrentItem(getActivity().getIntent().getIntExtra("order_position", 0), false);
            vp_gendan.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    GenDanFragment.this.position = position;
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
            pull_to_refresh_scrollView.setMode(PullToRefreshBase.Mode.BOTH);
            pull_to_refresh_scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ObservableScrollView>() {
                @Override
                public void onPullDownToRefresh(PullToRefreshBase<ObservableScrollView> refreshView) {
                    ((GendanCaseJine) orderFragments.get(position)).page = 1;
                    ((GendanCaseJine) orderFragments.get(position)).getFollowIndexData();
                }

                @Override
                public void onPullUpToRefresh(PullToRefreshBase<ObservableScrollView> refreshView) {
                    ((GendanCaseJine) orderFragments.get(position)).page++;
                    ((GendanCaseJine) orderFragments.get(position)).getFollowIndexData();
                }
            });
            initScrollViewListener();
        }
    }

    private void initScrollViewListener() {
        scrollView = pull_to_refresh_scrollView.getRefreshableView();

        scrollView.setScrollViewListener((scrollView, x, y, oldx, oldy) -> {
            //悬停tab
            int[] location = new int[2];
            tab_gendan.getLocationOnScreen(location);
            int yPosition = location[1];
            int visibleY = statusBarHeight + topLayoutHeight;
            Log.v("params", statusBarHeight + ">>" + topLayoutHeight + "  yPosition" + yPosition);

            if (yPosition <= visibleY) {
                tab_gendan.setVisibility(View.INVISIBLE);
                tab_gendan_2.setVisibility(View.VISIBLE);
            } else {
                tab_gendan_2.setVisibility(View.GONE);
                tab_gendan.setVisibility(View.VISIBLE);
            }
            if (yPosition - visibleY > maxDiff) {//获取最大间距
                maxDiff = yPosition - visibleY;
            }
//            PluLog.i("LHD PersonalCenterActivity    y = $yPosition   maxDiff = $maxDiff")
            //tab 渐变
            if (maxDiff <= 0) return;
            int diff = yPosition - visibleY;
            DecimalFormat df = new DecimalFormat("0.0");
//            PluLog.i("LHD  距离 = $diff  maxDiff = $maxDiff" + "   比例 = " + df.format(diff * 255 / maxDiff) + "  最终值 = " + df.format(diff * 255 / maxDiff))
            if (diff >= 0) {
                String valueLong = df.format(diff * 255 / maxDiff);
                String value = valueLong.substring(0, valueLong.length() - 2);
//                PluLog.i("LHD 最终透明值 ： $value")
                int alph = 255 - Integer.parseInt(value);
//                PluLog.i("LHD  透明值 = $alph    $value")
//                    relaTop.setBackgroundColor(Color.argb(alph, 47, 48, 47));
            } else {
//                    relaTop.setBackgroundColor(Color.argb(255, 47, 48, 47));
            }

            //上拉加载
            if (y == (scrollView.getChildAt(0).getMeasuredHeight() - scrollView.getMeasuredHeight())) {
                Log.i("LHD", "LHHD >>>>>>>>>>>>>  滑动到底部");
//                    ((GenDanHongRenDetailFragment)fragmentArrayList.get(vp_gendan_hot_people_detail.getCurrentItem())).loadMore();
//                    fragmentOne.loadMore();
            }
        });
    }

    int sort = 1, page = 1, page_size = 10;

    private void getFollowIndex() {
        userPresenter.getFollowIndex(sort, page, page_size, 0);
    }

    private void initHotPeopleData() {
        userPresenter.getHotPeopleList(1, 6);
    }

    private void initRecyclerViewData() {
        orderFragments = new ArrayList<>();
        //1综合排序 2认购金额 3跟单金额 4盈利率
        orderFragments.add(GendanCaseJine.newInstance(1));
        orderFragments.add(GendanCaseJine.newInstance(2));
        orderFragments.add(GendanCaseJine.newInstance(3));
        orderFragments.add(GendanCaseJine.newInstance(4));
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_more_hot_people:
                //红人列表
                startActivity(new Intent(getActivity(), BangDanActivity.class)
                        .putExtra("type", 1));
                break;
            case R.id.iv_my_attention:
                ((GendanCaseJine) orderFragments.get(position)).page = 1;
                if (((GendanCaseJine) orderFragments.get(position)).is_follow == 0) {
                    iv_my_attention.setText("我的关注");
                    tv_hot_gendan.setText("我的关注");
                    ((GendanCaseJine) orderFragments.get(position)).is_follow = 1;
                } else {
                    iv_my_attention.setText("热门跟单");
                    tv_hot_gendan.setText("热门跟单");
                    ((GendanCaseJine) orderFragments.get(position)).is_follow = 0;
                }
                ((GendanCaseJine) orderFragments.get(position)).getFollowIndexData();
                break;

        }
    }

    @Override
    public void success(@NotNull Object o, @NotNull String requestSuccessType) {
        dissDialog();
        if (requestSuccessType == userPresenter.getFollowIndex_SUCCESS) {
            pull_to_refresh_scrollView.onRefreshComplete();
        }
        if (requestSuccessType == userPresenter.getHotPeopleList_SUCCESS) {
            ArrayList<PeopleBean> peopleArray = (ArrayList<PeopleBean>) o;
            ar.addAll(peopleArray);
            ll_hot_user.removeAllViews();
            if (ar.size()<=0) {
                ll_hot_user.setVisibility(View.GONE);
                tv_no_hot_people.setVisibility(View.VISIBLE);
            }else{
                ll_hot_user.setVisibility(View.VISIBLE);
                tv_no_hot_people.setVisibility(View.GONE);
                for (int i = 0; i < ar.size(); i++) {
                    View view = View.inflate(getActivity(), R.layout.item_hotpeople, null);
                    TextView tv_hot_person1 = view.findViewById(R.id.tv_hot_person1);
                    ImageView iv_hot_person1 = view.findViewById(R.id.iv_hot_person1);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    layoutParams.setMargins(12, 6, 21, 6);
                    tv_hot_person1.setVisibility(View.GONE);
                    GlideUtil.display(getActivity(), ar.get(i).getHead_pic(), iv_hot_person1,R.mipmap.head_default);
                    view.setTag(ar.get(i).getUid());
                    view.setOnClickListener(view1 -> startActivity(new Intent(getActivity(), HotPeopleInfoActivity.class).putExtra("userId", view1.getTag().toString())));
                    ll_hot_user.addView(view, layoutParams);
                }
            }
        }
//        else if(){
//
//        }
    }

    @Override
    public void fail(int code, @NotNull Object msg, @NotNull String requestErrorType) {
        pull_to_refresh_scrollView.onRefreshComplete();
        dissDialog();
        if (requestErrorType == userPresenter.getFollowIndex_FAIL) {
            ByAlert.alert(msg);
            pull_to_refresh_scrollView.onRefreshComplete();
        } if (requestErrorType == userPresenter.getHotPeopleList_FAIL) {
            ByAlert.alert(msg);
        }
    }
}
